from os.path import join

import numpy as np
import cv2
import os

path = os.path.abspath('.')
path = join(path, '2.jpg')


def showSize(img, size):
    x = img.shape[0]
    y = img.shape[1]

    if x > size or y > size:
        mul_x = x // size
        mul_y = y // size
        if mul_x > mul_y:
            mul = mul_x + 1
        else:
            mul = mul_y + 1
    else:
        mul = 1
    width = y // mul
    height = x // mul
    return width, height


def showLine(inimg):
    gray = cv2.cvtColor(inimg,cv2.COLOR_BGR2GRAY)
    ret, thresh = cv2.threshold(gray,30,80,cv2.THRESH_BINARY)
    im2,contours,hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

    L = []
    for i in range(0,len(contours)):
        x,y,w,h = cv2.boundingRect(contours[i])
        L.append((w+h))
    print(max(L))

    for i in range(0,len(contours)):
        x,y,w,h = cv2.boundingRect(contours[i])
        if w+h == max(L):

            cv2.rectangle(inimg,(x,y),(x+w,y+h),(255,0,0),5)
    # img3 = cv2.Canny(thresh,0,255)
    # print(x,y,w,h)

    # return inimg
    return inimg


if __name__ == '__main__':
    img = cv2.imread(path)
    size = showSize(img, 600)
    end = showLine(img)
    size = showSize(end, 600)
    end=cv2.resize(end,size)
    cv2.imshow('1', end)
    # cv2.imshow('2', result)

    cv2.waitKey(0)
    cv2.destroyAllWindows()
